/*
 * ============================================================================
 *                   GNU Lesser General Public License
 * ============================================================================
 *
 *
 *
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 * 
 *
 *
 */
package rad.framework.jpa;

import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.Status;
import javax.transaction.UserTransaction;

/**
 * Extend this script to populate persistence data for a test.
 * 
 * @author boudyacho
 * 
 */
public abstract class TransactionScript {
	private String persistenceUnitJndiName = "";

	private InitialContext ctx = null;

	/**
	 * @param jndiName
	 *            of the EntityManagerFactory
	 */
	protected TransactionScript(String persistenceUnitJndiName) {
		this.persistenceUnitJndiName = persistenceUnitJndiName;
	}

	public Object run() throws Exception {
		EntityManagerFactory emf = (EntityManagerFactory) lookup(persistenceUnitJndiName);
		EntityManager em = emf.createEntityManager();
		UserTransaction t = (UserTransaction) lookup("UserTransaction");
		boolean hasTrans = t.getStatus() == Status.STATUS_ACTIVE;
		try {
			if (!hasTrans) {
				t.begin();
			}
			em.joinTransaction();
			Object result = run(em);// or do the work
			em.flush();
			if (!hasTrans) {
				t.commit();
			}
			return result;
		} catch (RuntimeException e) {
			if (!hasTrans) {
				t.rollback();
			}
			throw e;
		} catch (Throwable e) {
			if (!hasTrans) {
				t.rollback();
			}
			// TODO change to throws Throwable
			throw new Exception(e);
		} finally {
			em.close();
		}
	}

	protected Object lookup(String name) throws Exception {
		if (ctx == null) {
			ctx = new InitialContext();
		}
		return ctx.lookup(name);
	}

	/**
	 * Implement this to do the work.
	 */
	protected abstract Object run(EntityManager em) throws Exception;
}
